package com.dyh.quickdemozwei.deliver;

import com.google.common.collect.BiMap;
import com.google.common.collect.HashBiMap;
import org.apache.commons.collections4.CollectionUtils;

import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.function.Function;

public class OneOneReference  {
    BiMap<String,String> biMap = HashBiMap.create();

    public <T> void updateByAuto(List<T> datas, Function<T,String> tf, Function<T,String> tr){
        for (T data : datas) {
            biMap.put(tf.apply(data),tr.apply(data));
        }
    }

    public  void updateByAuto(String f,String r){
        biMap.put(f,r);
    }

    public String getForward(String k){
        return biMap.get(k);
    }

    public String getReverse(String k){
        return biMap.inverse().get(k);
    }



    public OneOneReference infer(OneOneReference other){

        OneOneReference resultReference = new OneOneReference();
        for (Map.Entry<String, String> entry : biMap.entrySet()) {
            String nv = other.getForward(entry.getValue());
            if (nv!=null){
                resultReference.updateByAuto(entry.getKey(),nv);
            }
        }
        return resultReference;

    }

    public OneManyReference infer(OneManyReference other){
        OneManyReference resultReference = new OneManyReference();

        for (Map.Entry<String, String> entry : biMap.entrySet()) {
            Set<String> nv = other.getForward(entry.getValue());
            if (!CollectionUtils.isEmpty(nv)){
                for (String s : nv) {
                    resultReference.updateByAuto(entry.getKey(),s);
                }
            }

        }

        return resultReference;
    }


    public ManyManyReference infer(ManyManyReference  other){
        ManyManyReference resultReference = new ManyManyReference();

        for (Map.Entry<String, String> entry : biMap.entrySet()) {
            Set<String> nv = other.getForward(entry.getValue());
            if (!CollectionUtils.isEmpty(nv)){
                for (String s : nv) {
                    resultReference.updateByAuto(entry.getKey(),s);
                }
            }
        }

        return resultReference;
    }


    public static void main(String[] args) {
        OneOneReference oneOneReference = new OneOneReference();
        oneOneReference.updateByAuto("k1","v1");
        oneOneReference.updateByAuto("k1","v11");
        oneOneReference.updateByAuto("k2","v2");

        System.out.println();
    }
}

